document.addEventListener('DOMContentLoaded', function() {
  // Get UI elements
  const activateToggle = document.getElementById('activateCanvas');
  const toolButtons = document.querySelectorAll('.tool-btn');
  const colorPicker = document.getElementById('colorPicker');
  const clearButton = document.getElementById('clear');
  const saveButton = document.getElementById('save');
  const undoButton = document.getElementById('undo');
  const redoButton = document.getElementById('redo');
  const statusMessage = document.createElement('div');
  
  // Add status message element
  statusMessage.className = 'status-message';
  document.querySelector('.container').appendChild(statusMessage);

  // Initialize state
  let currentTool = 'pen';
  let currentColor = '#FF0000';
  let isProcessing = false;
  let canUndo = false;
  let canRedo = false;
  let isContentScriptReady = false;
  let pendingMessages = [];

  // Show status message
  function showStatus(message, isError = false) {
    statusMessage.textContent = message;
    statusMessage.className = `status-message ${isError ? 'error' : 'success'}`;
    
    // 添加图标
    const icon = document.createElement('span');
    icon.className = 'status-icon';
    icon.textContent = isError ? '❌' : '✅';
    statusMessage.prepend(icon);
    
    // 自动隐藏
    const timeout = isError ? 5000 : 3000; // 错误消息显示更长时间
    setTimeout(() => {
      statusMessage.classList.add('fade-out');
      setTimeout(() => {
        statusMessage.textContent = '';
        statusMessage.className = 'status-message';
      }, 300);
    }, timeout);
  }

  // 检查与content script的连接
  async function checkContentScriptConnection() {
    try {
      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
      if (!tab) {
        throw new Error('No active tab found');
      }

      // 检查是否是Chrome系统页面
      if (tab.url.startsWith('chrome://') || tab.url.startsWith('chrome-extension://')) {
        showStatus('Cannot draw on Chrome system pages', true);
        return false;
      }

      const response = await chrome.tabs.sendMessage(tab.id, { action: 'checkConnection' });
      return response && response.success;
    } catch (error) {
      console.log('Connection check failed:', error);
      return false;
    }
  }

  // 改进的消息发送函数
  async function sendMessage(message, retries = 3) {
    try {
      // 首先检查连接
      if (!await checkContentScriptConnection()) {
        if (retries > 0) {
          console.log(`Connection failed, retrying... (${retries} attempts left)`);
          await new Promise(resolve => setTimeout(resolve, 500));
          return sendMessage(message, retries - 1);
        }
        throw new Error('Could not establish connection with the content script');
      }

      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
      const response = await chrome.tabs.sendMessage(tab.id, message);
      
      if (!response || !response.success) {
        throw new Error(response?.error || 'Operation failed');
      }

      return response;
    } catch (error) {
      console.error('Failed to send message:', error);
      showStatus(error.message, true);
      throw error;
    }
  }

  // 初始化函数
  async function initialize() {
    try {
      // 等待content script准备就绪
      let retries = 5;
      while (retries > 0 && !await checkContentScriptConnection()) {
        await new Promise(resolve => setTimeout(resolve, 200));
        retries--;
      }

      if (retries === 0) {
        showStatus('Failed to initialize extension', true);
        return;
      }

      // 加载保存的状态
      const result = await chrome.storage.local.get(['enabled', 'tool', 'color', 'canUndo', 'canRedo']);
      
      activateToggle.checked = result.enabled || false;
      currentTool = result.tool || 'pen';
      currentColor = result.color || '#FF0000';
      canUndo = result.canUndo || false;
      canRedo = result.canRedo || false;
      
      colorPicker.value = currentColor;
      updateToolButtons();
      updateHistoryButtons();
      updateToolStatus();
      
      if (result.enabled) {
        await sendMessage({ action: 'toggleCanvas', enabled: true });
      }
      
      console.log('Popup initialized successfully');
    } catch (error) {
      console.error('Failed to initialize popup:', error);
      showStatus('Failed to initialize', true);
    }
  }

  // 启动初始化
  initialize();

  // Update history buttons state
  function updateHistoryButtons() {
    undoButton.disabled = !canUndo;
    redoButton.disabled = !canRedo;
  }

  // Update tool status display
  function updateToolStatus() {
    const toolStatus = document.querySelector('.current-tool');
    const colorPreview = document.querySelector('.color-preview');
    
    // Update tool name
    toolStatus.textContent = currentTool.charAt(0).toUpperCase() + currentTool.slice(1) + ' Tool';
    
    // Update color preview
    colorPreview.style.backgroundColor = currentColor;
    colorPreview.style.width = '16px';
    colorPreview.style.height = '16px';
    colorPreview.style.display = 'inline-block';
    colorPreview.style.borderRadius = '50%';
    colorPreview.style.border = '1px solid #ddd';
  }

  // Toggle canvas activation
  activateToggle.addEventListener('change', async function() {
    if (isProcessing) return;
    isProcessing = true;
    
    try {
      const enabled = this.checked;
      await chrome.storage.local.set({ enabled });
      await sendMessage({
        action: 'toggleCanvas',
        enabled: enabled
      });
      showStatus(enabled ? 'Canvas activated' : 'Canvas deactivated');
    } catch (error) {
      console.error('Failed to toggle canvas:', error);
      this.checked = !this.checked; // Revert toggle
      showStatus('Failed to toggle canvas', true);
    } finally {
      isProcessing = false;
    }
  });

  // Tool selection
  toolButtons.forEach(button => {
    button.addEventListener('click', async function() {
      if (isProcessing) return;
      isProcessing = true;
      
      try {
        currentTool = this.id;
        await chrome.storage.local.set({ tool: currentTool });
        await sendMessage({
          action: 'changeTool',
          tool: currentTool
        });
        updateToolButtons();
        updateToolStatus(); // 更新工具状态显示
        showStatus(`Selected ${currentTool} tool`);
      } catch (error) {
        console.error('Failed to change tool:', error);
        showStatus('Failed to change tool', true);
      } finally {
        isProcessing = false;
      }
    });
  });

  // Color selection
  colorPicker.addEventListener('change', async function() {
    if (isProcessing) return;
    isProcessing = true;
    
    try {
      currentColor = this.value;
      await chrome.storage.local.set({ color: currentColor });
      await sendMessage({
        action: 'changeColor',
        color: currentColor
      });
      updateToolStatus(); // 更新工具状态显示
      showStatus('Color updated');
    } catch (error) {
      console.error('Failed to change color:', error);
      showStatus('Failed to change color', true);
    } finally {
      isProcessing = false;
    }
  });

  // Undo action
  undoButton.addEventListener('click', async function() {
    if (isProcessing || !canUndo) return;
    isProcessing = true;
    
    try {
      const response = await sendMessage({ action: 'undo' });
      canUndo = response.canUndo;
      canRedo = response.canRedo;
      await chrome.storage.local.set({ canUndo, canRedo });
      updateHistoryButtons();
      showStatus('Undo successful');
    } catch (error) {
      console.error('Failed to undo:', error);
      showStatus('Failed to undo', true);
    } finally {
      isProcessing = false;
    }
  });

  // Redo action
  redoButton.addEventListener('click', async function() {
    if (isProcessing || !canRedo) return;
    isProcessing = true;
    
    try {
      const response = await sendMessage({ action: 'redo' });
      canUndo = response.canUndo;
      canRedo = response.canRedo;
      await chrome.storage.local.set({ canUndo, canRedo });
      updateHistoryButtons();
      showStatus('Redo successful');
    } catch (error) {
      console.error('Failed to redo:', error);
      showStatus('Failed to redo', true);
    } finally {
      isProcessing = false;
    }
  });

  // Clear canvas
  clearButton.addEventListener('click', async function() {
    if (isProcessing) return;
    isProcessing = true;
    
    if (confirm('Are you sure you want to clear all drawings?')) {
      try {
        const response = await sendMessage({ action: 'clearCanvas' });
        canUndo = response.canUndo;
        canRedo = response.canRedo;
        await chrome.storage.local.set({ canUndo, canRedo });
        updateHistoryButtons();
        showStatus('Canvas cleared');
      } catch (error) {
        console.error('Failed to clear canvas:', error);
        showStatus('Failed to clear canvas', true);
      }
    }
    isProcessing = false;
  });

  // Save canvas
  saveButton.addEventListener('click', async function() {
    if (isProcessing) return;
    isProcessing = true;
    
    try {
      await sendMessage({ action: 'saveCanvas' });
      showStatus('Canvas saved');
    } catch (error) {
      console.error('Failed to save canvas:', error);
      showStatus('Failed to save canvas', true);
    } finally {
      isProcessing = false;
    }
  });

  // Listen for history state updates from content script
  chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    if (message.action === 'updateHistory') {
      canUndo = message.canUndo;
      canRedo = message.canRedo;
      chrome.storage.local.set({ canUndo, canRedo });
      updateHistoryButtons();
    } else if (message.action === 'contentScriptReady') {
      isContentScriptReady = true;
      console.log('Content script is ready');
      
      // 发送所有待处理的消息
      while (pendingMessages.length > 0) {
        const msg = pendingMessages.shift();
        sendMessage(msg);
      }
    }
    sendResponse({ success: true });
    return true;
  });

  // Helper function to update tool button states
  function updateToolButtons() {
    toolButtons.forEach(button => {
      button.classList.toggle('active', button.id === currentTool);
    });
  }

  // Helper function to get tool cursor
  function getToolCursor(tool) {
    switch (tool) {
      case 'pen':
        return 'crosshair';
      case 'highlighter':
        return `url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" style="font-size: 16px;"><text y="16">🖍️</text></svg>'), auto`;
      case 'eraser':
        return `url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" style="font-size: 16px;"><text y="16">🧹</text></svg>'), auto`;
      default:
        return 'default';
    }
  }
});
